import AliyunOSSUpload from '@/components/AliyunOSSUpload';
import { department_select } from '@/services/department';
import { add_edit_platformuser, filedlist } from '@/services/platformuser';
import { role_select } from '@/services/role';
import area from '@/utils/area';
import {
  ActionType,
  ProForm,
  ProFormDatePicker,
  ProFormGroup,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { Cascader, Divider, Form, message, Modal, Switch, Transfer, TreeSelect } from 'antd';
import CryptoJs from 'crypto-js';
import { useEffect, useState } from 'react';

interface Iprops {
  isShowAddModal: (show: boolean) => void;
  isAddModalOpen: boolean;
  actionRef: React.MutableRefObject<ActionType | undefined>;
}
type T = {
  disabled: boolean;
  status: number;
  value: any;
  id: any;
  title: any;
  name: any;
  pId: any;
  parent_id: any;
};

const AddStaff = (props: Iprops) => {
  const { isAddModalOpen, isShowAddModal, actionRef } = props;
  // 头像地址
  const [imageUrl, setImageUrl] = useState(undefined);
  // 存储科室列表
  const [departmentlist, setdepartmentlist] = useState();
  // 存储角色列表
  const [rolelist, setrolelist] = useState();
  // 穿梭框
  const [targetKeys, setTargetKeys] = useState<any>([]);
  const [selectedKeys, setSelectedKeys] = useState<any>([]);
  // 地区
  const [areaname, setareaname] = useState<any>();
  // 组件初始化渲染，获取科室列表与角色列表
  useEffect(() => {
    console.log('AddStaff组件加载完成');
    get_select_department();
    get_roles();
  }, []);
  // 新增员工
  const add_staff = async (value: Record<string, any>) => {
    // console.log('gjsfkhsfdjk', JSON.stringify(value.role?.map((item: string) => item + '')));

    if ('status' in value) {
      var switch_status = value.status ? 1 : 0;
    } else {
      var switch_status = 1;
    }
    //组织数据
    let request_body = {
      //必填项
      ...value,
      password: CryptoJs.MD5(value.password + 'f0c3c966').toString(),
      status: switch_status,
      //非必填项
      head_img: imageUrl,
      province_id: value.area ? value.area[0] : null,
      city_id: value.area ? value.area[1] : null,
      area_id: value.area ? value.area[2] : null,
      role_ids:
        value.role && value.role.length != 0
          ? JSON.stringify(value.role.map((item: string) => item + ''))
          : [],
    };
    let res: any = await add_edit_platformuser(request_body);
    console.log('新建员工', res);
    if (res.msg == 'ok') {
      actionRef.current?.reload();
      message.success('员工新建成功');
      isShowAddModal(false);
      onReset();
    } else {
      message.error(res.msg);
    }
  };

  // 获取科室列表
  const get_select_department = async () => {
    let params: any = await department_select();
    params.data.map((item: T) => {
      item.disabled = item.status == 0 ? true : false;
      item.value = item.id;
      item.title = item.name;
      item.pId = item.parent_id;
    });
    setdepartmentlist(params.data);
  };
  // 获取角色列表 穿梭框
  const get_roles = async () => {
    let params = await role_select();
    params.data.map((item: { key: string; id: string }) => {
      item.key = item.id;
    });
    setrolelist(params.data);
  };
  // 穿梭框相关方法
  const TransferonChange = (nextTargetKeys: any, direction: any, moveKeys: any) => {
    setTargetKeys(nextTargetKeys);
  };
  const TransferonSelectChange = (sourceSelectedKeys: any, targetSelectedKeys: any) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };
  // 获取职称列表 获取婚姻状况列表 获取学历列表 获取民族列表
  const get_system_field = async (key: any) => {
    let request_body = {
      type: key,
    };
    let params: any = await filedlist(request_body);
    let res: any = [];
    params.data.map((item: { value: string; key: string }) => {
      let temp: { label: string; value: string } = { label: '', value: '' };
      temp['label'] = item.value;
      temp['value'] = item.key;
      res.push(temp);
    });
    return res;
  };
  // 地区改变事件
  const area_onChange = (_: any, option: { name: string }[]) => {
    setareaname([option[0].name, option[1].name, option[2].name]);
  };
  // 重置表单
  const onReset = () => {
    //穿梭框
    setTargetKeys([]);
    //头像
    setImageUrl(undefined);
    //地区名称(额外处理)
    setareaname([]);
  };
  return (
    <Modal
      title="新增员工"
      centered
      open={isAddModalOpen}
      onCancel={() => {
        onReset();
        isShowAddModal(false);
      }}
      width={1200}
      destroyOnClose={true}
      footer={null}
    >
      <Divider />
      <ProForm
        onReset={() => onReset()}
        onFinish={(value) => add_staff(value)}
        submitter={{
          searchConfig: {
            submitText: '提交',
            resetText: '重置',
          },
          resetButtonProps: {
            style: {
              // 隐藏重置按钮
              display: 'block',
              position: 'absolute',
              left: 'calc(50% - 107px)',
            },
          },
          submitButtonProps: {
            style: {
              display: 'block',
              position: 'absolute',
              right: 'calc(50% - 107px)',
            },
          },
        }}
      >
        <div style={{ display: 'flex' }}>
          <div style={{ width: '70%', flex: '6' }}>
            <ProFormGroup>
              <ProFormText
                width={280}
                name="username"
                label="员工姓名"
                placeholder="请输入员工姓名"
                rules={[
                  {
                    required: true,
                    message: '请输入员工姓名',
                    validateTrigger: 'onBlur',
                  },
                  { pattern: /(^\S)((.)*\S)?(\S*$)/, message: '不能输入空格' },
                ]}
              />
              <ProFormSelect
                width={280}
                request={async () => [
                  { label: '未知', value: 0 },
                  { label: '男', value: 1 },
                  { label: '女', value: 2 },
                ]}
                name="sex"
                label="性别"
                rules={[
                  {
                    required: true,
                    message: '请选择性别',
                  },
                ]}
              />
              <ProFormDatePicker
                name="birth"
                label="出生日期"
                width={280}
                rules={[
                  {
                    required: true,
                    message: '请选择出生日期',
                  },
                ]}
              />
              <ProFormText
                width={280}
                name="phone"
                label="手机号"
                placeholder="请输入员工手机号"
                rules={[
                  {
                    required: true,
                    message: '请输入员工手机号',
                    validateTrigger: 'onBlur',
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: '请输入正确的手机号',
                    validateTrigger: 'onBlur',
                  },
                ]}
              />
              <Form.Item
                name="department_id"
                label="所属科室"
                rules={[{ required: true, message: '请选择所属科室' }]}
              >
                <TreeSelect
                  treeDataSimpleMode
                  style={{ width: '280px' }}
                  treeData={departmentlist}
                  placeholder="请选择科室"
                  treeDefaultExpandAll
                />
              </Form.Item>
              <ProFormSelect
                width={280}
                request={async () => get_system_field('doctor_positional')}
                name="positional"
                label="职称"
                rules={[
                  {
                    required: true,
                    message: '请选择职称',
                  },
                ]}
              />
              <ProFormSelect
                width={280}
                request={async () => get_system_field('marital_status')}
                name="marital_status"
                label="婚姻状况"
              />
              <ProFormSelect
                width={280}
                request={async () => get_system_field('education')}
                name="education"
                label="学历"
              />
              <ProFormSelect
                width={280}
                request={async () => get_system_field('nation_type')}
                name="nation_type"
                label="民族"
              />
              <Form.Item name="area" label="地址">
                <Cascader
                  style={{ width: '280px' }}
                  options={area}
                  onChange={area_onChange}
                  placeholder="请选择地区"
                  fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                />
              </Form.Item>
              <ProFormText
                width={280}
                name="address"
                label="详细地址"
                placeholder="请输入详细地址"
              />
              <ProFormText.Password
                width={280}
                name="password"
                label="密码"
                placeholder="请输入密码"
                rules={[
                  {
                    required: true,
                    message: '请输入密码',
                    validateTrigger: 'onBlur',
                  },
                  {
                    pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$/,
                    message: '密码必须是6-16位的字母加数字组合',
                    validateTrigger: 'onBlur',
                  },
                ]}
              />
            </ProFormGroup>
          </div>
          <div style={{ width: '30%', flex: '1' }}>
            <ProForm.Item name="head_img" label="头像">
              <div>
                <AliyunOSSUpload imageUrl={imageUrl} setImageUrl={setImageUrl}></AliyunOSSUpload>
              </div>
            </ProForm.Item>
            <Form.Item name="status" label="状态" valuePropName="checked">
              <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked={true} />
            </Form.Item>
          </div>
        </div>
        <Form.Item name="role" label="设置角色">
          <Transfer
            dataSource={rolelist}
            titles={['角色列表', '已有角色']}
            targetKeys={targetKeys}
            selectedKeys={selectedKeys}
            onChange={TransferonChange}
            onSelectChange={TransferonSelectChange}
            render={(item) => item.rolename}
            listStyle={{
              width: 520,
              height: 300,
            }}
          />
        </Form.Item>
        <br />
      </ProForm>
      <br />
    </Modal>
  );
};
export default AddStaff;
